﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using Wedn.Core.Service;
using Wedn.Core.Entity;
using Wedn.Core.Utility;
using Wedn.Core.Common;

namespace Wedn.TemplateEngine.UC
{
    /// <summary>
    /// 自定义模版页和模块可以选择从此类派生, 从而获得数据 在需要调用数据时直接调用方法名(例如:"<%=GetTitle()%>")
    /// 如果使用系统默认的CodeBehind技术, 则隐藏类需继承自Template. 
    /// </summary>
    public class Template : UserControl
    {
        private IDictionary<string, object> dict;
        /// <summary>
        /// 初始化标签字典
        /// </summary>
        public void SetDict(IDictionary<string, object> dict)
        {
            this.dict = dict;
        }
        /// <summary>
        /// 增加一对键值对
        /// </summary>
        /// <param name="kv">键值对</param>
        public void SetDict(KeyValuePair<string, object> kv)
        {
            if (!dict.Keys.Contains(kv.Key))
            {
                this.dict.Add(kv);
                return;
            }
            else
            {
                this.dict[kv.Key] = kv.Value;
            }
        }
        /// <summary>
        /// 数据字典索引器
        /// </summary>
        /// <param name="index">索引</param>
        /// <returns>值</returns>
        public object this[string index]
        {
            get
            {
                string temp = index.ToLower();
                if (dict.Keys.Contains(temp))
                {
                    return dict[temp];
                }
                return null;
            }
        }

        /// <summary>
        /// 获取跟站点有关信息数据, 返回查询到的字符串, 如果不存在则返回null
        /// </summary>
        /// <param name="key">指定查选的名称, 参照说明</param>
        /// <returns>查询到的字符串, 如果不存在则返回null</returns>
        public string SiteInfo(string key)
        {
            return dict[key.ToLower()].ToString();
        }
        /// <summary>
        /// 文章管理对象
        /// </summary>
        PostManager postManager = new PostManager();
        private List<Post> posts;
        /// <summary>
        /// 文章集合
        /// </summary>
        public List<Post> Posts
        {
            get
            {
                if (posts == null)
                {
                    string tempIndex = RequestHelper.QueryString("page", true);
                    int pageIndex = StringHelper.StrToInt(tempIndex, 1);
                    string tempSize = Setting.PageSize;
                    int pageSize = StringHelper.StrToInt(tempSize, 10);
                    posts = postManager.GetPostList(PostStatus.Pubilc, PostType.Post, pageSize, pageIndex, "post_pubdate", 0);
                }
                return posts;
            }
        }

        /// <summary>
        /// 文章详情
        /// </summary>
        public Post PostDetail
        {
            get
            {
                int id = RequestHelper.QueryInt("post");
                string sulg = RequestHelper.QueryString("name");
                if (string.IsNullOrEmpty(sulg))
                {
                    foreach (Post item in Posts)
                    {
                        if (item.Id == id)
                        {
                            return item;
                        }
                    }
                    return postManager.GetPost(id);
                }
                else
                {
                    foreach (Post item in Posts)
                    {
                        if (item.Slug == sulg)
                        {
                            return item;
                        }
                    }
                    return postManager.GetPost(sulg);
                }
            }
        }
        /// <summary>
        /// 文章集合分页链接Html
        /// </summary>
        public string PagedLink
        {
            get
            {
                //<span class="current">1</span><a href="" class="inactive">2</a><a href="" class="inactive">3</a>
                StringBuilder sbd = new StringBuilder();
                string tempSize = Setting.PageSize;
                int pageSize = StringHelper.StrToInt(tempSize, 10);

                string postCount = Setting.SitePostCount;
                int count = StringHelper.StrToInt(postCount, 0);
                int pageCount = (int)Math.Ceiling((double)count / pageSize);

                string tempIndex = RequestHelper.QueryString("page", true);
                int pageIndex = StringHelper.StrToInt(tempIndex, 1);
                for (int i = 1; i <= pageCount; i++)
                {
                    if (i == pageIndex)
                    {
                        sbd.Append(string.Format("<span class=\"current\">{0}</span>", i));
                    }
                    else
                    {
                        sbd.Append(string.Format("<a href=\"{0}page/{1}\" class=\"inactive\">{1}</a>", Config.SiteUrl, i));
                    }
                }
                return sbd.ToString();
            }
        }

        public List<Comment> GetComments(Post p)
        {
            return p.Comments.FindAll(delegate(Comment other) { return other.ParentId == 0; });
        }

        public void LoadChildComments(Comment comment)
        {
            string temp = @"<li class=""depth-{0}"">
                                            <div class=""comment-body"">
                                                <div class=""vcard"">
                                                    <img alt=""{1}"" src=""http://0.gravatar.com/avatar/{2}?s=40"" class=""avatar"">
                                                    <strong><a href=""#"">{1}</a></strong>:&nbsp;&nbsp;<a href=""#"" title=""编辑评论"">编辑</a>
                                                </div>
                                                <p>{3}</p>
                                                <div class=""clear""></div>
                                                <span class=""datetime"">{4}</span><span class=""reply""><a class=""comment-reply-link"" href=""#"">[回复]</a></span>
                                            </div>
                                        </li>";
            List<Comment> c = comment.ChildComments;
            for (int i = 0; i < c.Count; i++)
            {
                Response.Write(@"<ul class=""children"">");
                Response.Write(string.Format(temp, i, c[i].Auther, StringHelper.Encrypt(c[i].AutherEmail, "md5"), c[i].Content, c[i].PubDate.ToString("yyyy-MM-dd")));
                LoadChildComments(c[i]);
                Response.Write(@"</ul>");
            }
        }

        /// <summary>
        /// 根据模版文件名加载模板
        /// </summary>
        /// <param name="templateName">模版文件名</param>
        public void Include(string templateName)
        {
            TemplateHelper th = new TemplateHelper();
            th.Load(string.Format("/themes/{0}/templates/{1}", Setting.Theme, templateName));
            th.Set((Dictionary<string, object>)dict);
            //th.Render(Page.Response.Output);
            th.Render(Response.Output);
            //return th.ToHTML();
        }

        public void LoadSidebar()
        {
            string[] widgets = Setting.Dict["Widgets"].ToString().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (widgets.Length > 0)
            {
                TemplateHelper th = new TemplateHelper();
                foreach (var item in widgets)
                {
                    th.Load(string.Format("/widgets/w_{0}.ascx", item));
                    th.Render(Response.Output);
                }
                th.Set((Dictionary<string, object>)dict);
            }
        }
    }
}
